<template>
  <div v-if="actItem" class="itemCom">
    <van-nav-bar
      :title="actItem.name"
      :left-text="editBool?'全选':'返回'"
      :right-text="editBool?'取消':'编辑'"
      :left-arrow="!editBool"
      @click-left="back"
      @click-right="edit"
    />
    <div class="btnBar" v-if="editBool">
      <van-button type="primary" @click="editItem">编辑分组名称</van-button>
      <van-button type="danger" @click="delItem">删除分组</van-button>
    </div>
    <div class="list">
      <div class="bookList" v-for="(v,i) in actItem.list" :key="i">
        <div class="img">
          <img :src="v.image" alt />
        </div>
        <div class="name">{{v.name}}</div>
        <div class="mask" v-if="v.checked"></div>
        <van-checkbox class="checkboxClass" v-model="v.checked" shape="square"></van-checkbox>
      </div>
    </div>
    <!-- 告诉footerbar 是item删除还是cartlist删除 -->
    <FooterBar v-if="editBool" :checkList='checkList' :itemId='actItem.itemId'/>
    <!-- 修改分组名称 -->
    <van-dialog v-model="editItemBool" title="修改分组名称" show-cancel-button @confirm="editItemNameFun">
      <van-field v-model="itemName" label="文本" placeholder="请输入用户名" />
    </van-dialog>
  </div>
</template>

<script>
import FooterBar from "../../../components/footerBar/footerBar";
export default {
  props: ["actItem"],
  data() {
    return {
      editBool: false,
      editItemBool: false,
      itemName: null
    };
  },
  computed: {
      checkList() {
          return this.actItem.list.filter(v=> {
              return v.checked
          })
      },
      haveBook() {
          return this.$store.itemList
      }
  },
  watch: {
      // 监听是否还有书
      haveBook() {
          console.log(this.haveBook)
          if(!this.haveBook) {
              // 没有书删除分组 
              this.delItem()
              this.$emit('back')
          }
      }
  },
  methods: {
    back() {
      if (!this.editBool) {
        // 返回
        this.$emit("back");
      } else {
        // 全选
      }
    },
    edit() {
      this.editBool = !this.editBool;
    },
    editItem() {
      this.itemName = this.actItem.name;
      this.editItemBool = true;
    },
    editItemNameFun() {
      // 修改分组名称的mutation方法
      this.$store.commit("editItemName", {
        id: this.actItem.itemId,
        name: this.itemName
      });
    },
    delItem() {
      // 删除当前分组 并且把list数据重新放回cartList
      this.actItem.list.forEach((v, i) => {
        // 加到书架 在我删除分组之前
        this.$store.commit("addToCart", v);
      });

      this.$store.commit("delItem", this.actItem.itemId);
      this.$emit("back");
    }
  },
  components: {
    FooterBar
  }
};
</script>

<style lang='scss' scoped>
.itemCom {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: fixed;
  top: 0;
  left: 0;
  background: #fff;
}
</style>